package com.newlink.building.userinfo.activity

import android.content.Intent
import android.text.Editable
import android.text.TextWatcher
import android.view.View
import android.widget.TextView
import androidx.lifecycle.lifecycleScope
import com.newlink.building.common_base.base.NL_BaseMvpActivity
import com.newlink.building.common_base.base.NL_OnActivityCallback
import com.newlink.building.common_base.manager.Base_CountryCodeManager
import com.newlink.building.common_base.model.bean.CountryCodeBean
import com.newlink.building.common_base.utils.NLog
import com.newlink.building.common_base.utils.ToastUtils
import com.newlink.building.common_base.utils.countrycode.Base_CountryCodeSelectActivityNL
import com.newlink.building.userinfo.R
import com.newlink.building.userinfo.databinding.ActivityAccountInformationChangePhoneNewPhoneBinding
import com.newlink.building.userinfo.mvp.Module_UserInfo_AccountInformationChangePhoneNewPhonePresenter
import com.newlink.building.userinfo.mvp.contract.Module_UserInfo_AccountInformationChangePhoneNewPhoneContract
import kotlinx.coroutines.launch

/**
 * @author wangyang
 * @date 2022/10/28
 * @description 我的——账户信息——更换手机号页面（第二步：输入新手机号）
 */
class Module_UserInfo_AccountInformationChangePhoneNewPhoneActivityNL :
    NL_BaseMvpActivity<Module_UserInfo_AccountInformationChangePhoneNewPhoneContract.View, Module_UserInfo_AccountInformationChangePhoneNewPhoneContract.Presenter>(),
    Module_UserInfo_AccountInformationChangePhoneNewPhoneContract.View, View.OnClickListener {

    private var countryCodeList: MutableList<CountryCodeBean> = mutableListOf()
    private var mDefaultCountryCodeBean: CountryCodeBean? = null
    private var mPhoneNumber: String? = null
    private var mArea: String? = null

//    override fun attachLayoutRes(): Int =
//        R.layout.activity_account_information_change_phone_new_phone

    private lateinit var mBinding: ActivityAccountInformationChangePhoneNewPhoneBinding
    override fun attachLayoutRes(): View {
        mBinding = ActivityAccountInformationChangePhoneNewPhoneBinding.inflate(layoutInflater)
        return mBinding.root
    }

    override fun initData() {
        if (mAllCountryList.isEmpty()) {
            showLoading()
            loadDefaultCountryCode()
        } else {
            countryCodeList = mAllCountryList
            mDefaultCountryCodeBean = mDefaultCountryBean
        }
    }

    private fun loadDefaultCountryCode() {
        if (mAllCountryList.isEmpty()) {
            lifecycleScope.launch {
                mAllCountryList =
                    Base_CountryCodeManager.getCountryCodeBeanList(applicationContext).toMutableList()
                mDefaultCountryBean = Base_CountryCodeManager.getDefaultCountryCode(applicationContext)
                NLog.e("[jake] :::  Login ::: country list :: ${mAllCountryList.size}")
                NLog.e("[jake] :::  Login ::: country default ::${mDefaultCountryBean?.locale}")
            }
        }
    }

    override fun initView() {
        findViewById<TextView>(R.id.tv_title_bar_center).text =
            resources.getText(R.string.account_information_change_phone_title)

        mBinding.tvDescribe.text =
            getString(R.string.account_information_change_phone_new_phone_describe, "17801063494")

        mBinding.ivClear.setOnClickListener(this)
        mBinding.btnGetCode.setOnClickListener(this)

        //手机号的输入框监听
        mBinding.etPhone.addTextChangedListener(object : TextWatcher {
            override fun beforeTextChanged(s: CharSequence?, start: Int, count: Int, after: Int) {
            }

            override fun onTextChanged(s: CharSequence?, start: Int, before: Int, count: Int) {
            }

            override fun afterTextChanged(s: Editable?) {
                checkChangeButtonState()
            }

        })

        mBinding.selectCountry.text = "+" + countryCode.ifEmpty { "86" }
        mBinding.selectCountry.setOnClickListener {
            val intent = Intent(
                this@Module_UserInfo_AccountInformationChangePhoneNewPhoneActivityNL,
                Base_CountryCodeSelectActivityNL::class.java
            )

            startActivityForResult(intent, object : NL_OnActivityCallback {
                override fun onActivityResult(resultCode: Int, data: Intent?) {
                    if (resultCode == 1_000_008) {
                        val defaultCountryCode = data?.getStringExtra("default_country_code")
                        if (defaultCountryCode?.isNotEmpty() == true) {
                            mBinding.selectCountry.text = "+ $defaultCountryCode"
                            countryCode = defaultCountryCode
                        }
                    }
                }
            })
        }
    }

    override fun onClick(v: View?) {
        when (v?.id) {
            R.id.iv_clear -> {
                //清除输入
                mBinding.etPhone.setText("")
            }

            R.id.btn_get_code -> {

                mPhoneNumber = mBinding.etPhone.text.toString()
                mArea = countryCode
                if (mPhoneNumber.isNullOrEmpty()) {
                    ToastUtils.showTextToast(
                        this@Module_UserInfo_AccountInformationChangePhoneNewPhoneActivityNL,
                        getString(R.string.bind_phone_warning)
                    )
                } else if (mArea.isNullOrEmpty()) {
                    ToastUtils.showTextToast(
                        this@Module_UserInfo_AccountInformationChangePhoneNewPhoneActivityNL,
                        getString(R.string.bind_phone_warning)
                    )
                } else {
                    mPresenter?.getChangePhoneVerifyCode(accessToken, mArea!!, mPhoneNumber!!)
                }
            }
        }
    }

    /**
     * 修改按钮的状态
     */
    fun checkChangeButtonState() {
        val inputPhone = mBinding.etPhone.text.trim().toString()

        mBinding.btnGetCode.isEnabled = inputPhone.isNotEmpty()
    }

    override fun createPresenter(): Module_UserInfo_AccountInformationChangePhoneNewPhoneContract.Presenter =
        Module_UserInfo_AccountInformationChangePhoneNewPhonePresenter()

    override fun showData() {
    }

    override fun getVerifyCodeSuccess() {
        val intent = Intent(
            this,
            Module_UserInfo_AccountInformationChangePhoneInputCodeActivityNL::class.java
        )
        intent.putExtra("bind_phone", mPhoneNumber)
        intent.putExtra("bind_area", mArea)
        startActivity(intent)
        finish()
    }

    override fun getVerifyCodeFailed(msg: String?) {
        msg?.let {
            ToastUtils.showTextToast(applicationContext, it)
        }
    }
}